package com.gin.kotlin.no_gay_alliance.listener

import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.MenuItem
import android.widget.ArrayAdapter
import android.widget.EditText
import androidx.activity.result.ActivityResultLauncher
import androidx.appcompat.widget.PopupMenu
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.PostActivity.Companion.obtainIntent
import com.gin.kotlin.no_gay_alliance.activity.ReplyListActivity
import com.gin.kotlin.no_gay_alliance.activity.SourceCodeActivity
import com.gin.kotlin.no_gay_alliance.activity.UseItemActivity
import com.gin.kotlin.no_gay_alliance.adapter.reply.EditHistoryAdapter
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.argument.EditHistoryArgument
import com.gin.kotlin.no_gay_alliance.argument.PostPrepareArgument
import com.gin.kotlin.no_gay_alliance.argument.PostPrepareArgument.Action
import com.gin.kotlin.no_gay_alliance.argument.ReplyListArgument
import com.gin.kotlin.no_gay_alliance.argument.ReplyListArgument.Type
import com.gin.kotlin.no_gay_alliance.base.AlertDialogUtils
import com.gin.kotlin.no_gay_alliance.base.ClipboardUtils
import com.gin.kotlin.no_gay_alliance.base.InputMethodUtils
import com.gin.kotlin.no_gay_alliance.base.MyHandler
import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.kotlin.no_gay_alliance.database.entity.ReportHistory
import com.gin.kotlin.no_gay_alliance.database.entity.TopicBookmark
import com.gin.kotlin.no_gay_alliance.databinding.DialogReportBinding
import com.gin.kotlin.no_gay_alliance.fragment.topiclist.UserSearchFragment
import com.gin.kotlin.no_gay_alliance.provider.ngaphp.EditHistoryProvider
import com.gin.kotlin.no_gay_alliance.provider.ngaphp.FavorFolderProvider.Companion.showFolderDialog
import com.gin.kotlin.no_gay_alliance.store.GlobalProperty
import com.gin.nga.callback.NgaCallback
import com.gin.nga.response.base.NgaResponse
import com.gin.nga.response.reply.EditHistory
import com.gin.nga.response.reply.ReplyInfo
import com.gin.nga.response.topic.TopicDetail
import retrofit2.Call
import retrofit2.Response
import java.time.ZonedDateTime

/**
 * 回复中的底部按钮激活的[PopupMenu]，菜单项点击响应
 * @property context Context
 * @property forumId Long?
 * @property forumName String?
 * @property onlyAuthor 是否为只看TA模式
 * @constructor
 */
data class ReplyPopupMenuListener(
    val context: Context,
    val launcher: ActivityResultLauncher<Intent>,
    val handler: MyHandler? = null,
    val replyInfo: ReplyInfo? = null,
    val forumId: Long? = null,
    val forumName: String? = null,
    val onlyAuthor: Long? = null,
    val topic: TopicDetail? = null,
    val page: Int? = null,
) : PopupMenu.OnMenuItemClickListener, NgaCallback<List<String>> {

    /**
     * 请求成功回调
     * @param data 响应数据
     */
    override fun onSuccess(call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, data: List<String>?) {
        handler?.toast(body?.error?.get(0) ?: data?.get(0))
    }


    override fun onError(call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, errorMessage: String) {
        handler?.toast(errorMessage)
    }

    override fun onMenuItemClick(item: MenuItem?): Boolean {
        val replyInfo = this.replyInfo ?: return true

        val itemId = item?.itemId
        val userId = replyInfo.authorUid?.toLongOrNull()
        val topicId = replyInfo.topicId
        val username = replyInfo.anonymousName ?: replyInfo.userInfo?.username ?: ""
        val replyId = replyInfo.replyId
        // 用户菜单
        if (userId != null) {
            when (itemId) {
                R.id.mi_use_item -> UseItemActivity.start(context, userId)
                // 只看TA
                R.id.mi_user_only -> ReplyListActivity.startActivity(context, ReplyListArgument(Type.LIST, userId = userId, topicId = topicId, title = "只看: $username"))
                R.id.mi_user_topic -> UserSearchFragment.startActivityTopic(context = context, userId, title = "$username 的主题")
                R.id.mi_user_topic_forum -> UserSearchFragment.startActivityTopic(context = context, userId, forumId = forumId, title = "$username 在[$forumName]的主题")
                R.id.mi_user_topic_recommend -> UserSearchFragment.startActivityTopic(
                    context = context,
                    userId,
                    forumId = forumId,
                    recommendOnly = true,
                    title = "$username 在[$forumName]的精华"
                )

                R.id.mi_user_reply -> UserSearchFragment.startActivityReply(context = context, userId, title = "$username 的回复")
                R.id.mi_user_reply_forum -> UserSearchFragment.startActivityReply(context = context, userId, title = "$username 在[$forumName]的回复", forumId = forumId)
            }
        }

        // 分享菜单
        when (itemId) {
            R.id.mi_copy_link -> {
                replyInfo.obtainUrl(GlobalProperty.getInstance().domain)?.also {
                    Log.i(TAG, "已复制: $replyInfo")
                    ClipboardUtils.setText(it, context)
                    handler?.toast("已复制链接")
                }
            }

            R.id.mi_copy_code -> {
                Log.i(TAG, "已复制: ${replyInfo.getBbsCode()}")
                ClipboardUtils.setText(replyInfo.getBbsCode(), context)
                handler?.toast("已复制代码")
            }
        }

        val readApi = App.INSTANCE.ngaApi.topicReadApi
        val noticeApi = App.INSTANCE.ngaApi.noticeApi
        // 更多菜单
        if (topicId != null) when (itemId) {
            // 引用
            R.id.mi_quote -> launcher.launch(obtainIntent(context, PostPrepareArgument(Action.QUOTE, topicId = topicId, replyId = replyId)))
            // 评论
            R.id.mi_comment -> launcher.launch(obtainIntent(context, PostPrepareArgument(Action.REPLY, topicId = topicId, replyId = replyId, isComment = true)))
            //编辑
            R.id.mi_edit -> launcher.launch(obtainIntent(context, PostPrepareArgument(Action.MODIFY, topicId = topicId, replyId = replyId)))
            //开提醒
            R.id.mi_notice_on -> noticeApi.enable(0, topicId = topicId, replyId = replyId).enqueue(this)
            //关提醒
            R.id.mi_notice_off -> noticeApi.enable(1, topicId = topicId, replyId = replyId).enqueue(this)
            //举报
            R.id.mi_report -> {
                // 弹窗填写举报理由
                val binding = DialogReportBinding.inflate(LayoutInflater.from(context))
                binding.tvReportHeader.text = context.getString(R.string.tv_report_header, username)
                binding.acTvReportReason.setAdapter(
                    ArrayAdapter(context, android.R.layout.simple_dropdown_item_1line, listOf("挖坟", "海豹", "造谣", "引战", "人身攻击", "广告"))
                )
                binding.acTvReportReason.requestFocus()
                binding.acTvReportReason.setSelection(0)
                // 自动显示选项
                handler?.postDelayed({ binding.acTvReportReason.showDropDown() }, 300)

                AlertDialogUtils.builder(context, contentView = binding.root, listener = { _, which ->
                    if (which == DialogInterface.BUTTON_POSITIVE) {
                        val reason = binding.acTvReportReason.text.toString()
                        readApi.report(topicId, replyId, reason).enqueue(object : NgaCallback<List<String>> {
                            override fun onSuccess(
                                call: Call<NgaResponse<List<String>>>,
                                response: Response<NgaResponse<List<String>>>,
                                body: NgaResponse<List<String>>?,
                                data: List<String>?
                            ) {
                                handler?.toast(body?.error?.get(0) ?: data?.get(0))

                                //保存举报历史
                                val reportHistory = ReportHistory(
                                    username = username,
                                    userId = userId?.takeIf { it > 0 },
                                    topicId = topicId,
                                    replyId = replyId?.takeIf { it > 0 },
                                    title = topic?.title ?: "",
                                    content = replyInfo.content ?: "",
                                    reason = reason
                                )
                                App.INSTANCE.database.reportHistoryDao().add(reportHistory)
                            }


                            override fun onError(
                                call: Call<NgaResponse<List<String>>>,
                                response: Response<NgaResponse<List<String>>>,
                                body: NgaResponse<List<String>>?,
                                errorMessage: String
                            ) {
                                handler?.toast(errorMessage)
                            }
                        })
                    }
                }).show()
            }
            // 收藏回复
            R.id.mi_add_favor_topic -> showFolderDialog(context, topicId, replyId)
            // 礼物
            R.id.mi_gift -> UseItemActivity.start(context, topicId, replyId)
            // 源码
            R.id.mi_source_code -> SourceCodeActivity.start(context, replyInfo.content ?: "")
            //编辑历史
            R.id.mi_edit_history -> {
                EditHistoryProvider.getInstance().enqueue(EditHistoryArgument(topicId, replyId), callback = object : RCallback<List<EditHistory>, EditHistoryArgument> {
                    override fun onSuccess(data: List<EditHistory>, ignoreCache: Boolean) {
                        val adapter = EditHistoryAdapter(context, handler!!).also { it.replaceData(data) }
                        val recyclerView = RecyclerView(context).also {
                            it.layoutManager = LinearLayoutManager(context)
                            it.adapter = adapter
                        }
                        AlertDialogUtils.builder(context, title = "编辑历史", message = "点击打开", contentView = recyclerView).show()
                    }

                    override fun onError(errorMessage: String) {
                    }
                })

            }
            // 添加书签
            R.id.mi_bookmark_add -> {
                val editText = EditText(context)
                editText.hint = "请输入备注(可选)"
                editText.requestFocus()
                editText.selectAll()

                AlertDialogUtils.builder(context, title = "添加书签", contentView = editText, listener = { _, which ->
                    if (which == DialogInterface.BUTTON_POSITIVE) {
                        val dao = App.INSTANCE.database.topicBookmarkDao()
                        dao.add(
                            TopicBookmark(
                                id = 0,
                                topicId = topicId,
                                page = page!!,
                                floorNumber = replyInfo.floorNumber!!,
                                timestamp = ZonedDateTime.now(),
                                userId = onlyAuthor,
                                username = onlyAuthor?.let { username },
                                remark = editText.text.toString()
                            )
                        )
                        handler?.toast("已添加书签")
                    }
                }).show()

                handler?.postDelayed({ InputMethodUtils.show(editText, context) }, 200)
            }
        }



        return true
    }

    companion object {
        private fun toast(message: String?) = message?.also { App.INSTANCE.handler?.toast(it) }
        private val TAG = ReplyPopupMenuListener::class.java.simpleName
    }
}